package com.hhhn.wk.main.tab4.allorder.activity.starsendgoos;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hhhn.wk.R;
import com.hhhn.wk.base.BaseActivity;
import com.hhhn.wk.main.tab4.allorder.entity.ItemGoodsBean;
import com.hhhn.wk.utils.AllPublic;
import com.hhhn.wk.utils.Constants;
import com.hhhn.wk.widget.adapter.MyAdaper;
import com.hhhn.wk.widget.adapter.ViewHolder;
import com.hhhn.wk.widget.customview.MyListView;
import com.hhhn.wk.widget.select_img.adapter.PickAdapter;
import com.imnjh.imagepicker.SImagePicker;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.http.body.MultipartBody;
import org.xutils.x;

import java.io.File;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * * * * * * * * * * * *
 * @author：文珂    ｡◕‿◕｡ *
 * Data：2018/4/14 0014    ｡◕‿◕｡ *
 * Function：      ｡◕‿◕｡ *
 * 申请退款页面
 * * * * * * * * * * * */
public class ApplyActivity extends BaseActivity {
    DecimalFormat df   = new DecimalFormat("######0.00");
    ArrayList<String> pathList=new ArrayList<>();
    private static final String TAG ="ApplyActivity" ;
    private TextView tv_title;
    public static final String AVATAR_FILE_NAME = "avatar.png";
    public static final int REQUEST_CODE_AVATAR = 100;
    public static final int REQUEST_CODE_IMAGE = 101;
    private ImageView mImageView;
    private BaseActivity activity;
    private GridView gridView;
    private PickAdapter pickAdapter;

    private TextView tv_refundMoney;
    private double refundMoney=0;
    private int position=0;
    private List<ItemGoodsBean> lstBean=new ArrayList<ItemGoodsBean>();
    private MyListView mLoadListView;
    private MyAdaper<ItemGoodsBean> myAdaper;
    private EditText et_refund;
    private LinearLayout ll_login;
    Intent intent;


    @Override
    protected void setOnCreateContentView() {
        setContentView(R.layout.activity_apply);
        activity=this;
         intent=getIntent();
        position=intent.getIntExtra("position",1);
        lstBean = (ArrayList<ItemGoodsBean>) intent.getSerializableExtra("lstBean");
    }

    @Override
    protected void initView() {

        ll_login=findViewById(R.id.ll_login);
        et_refund=findViewById(R.id.et_refund);
        tv_refundMoney=findViewById(R.id.tv_refundMoney);
        mLoadListView=findViewById(R.id.mLoadListView);
        mImageView=findViewById(R.id.mImageView);
        tv_title=findViewById(R.id.tv_title);
        pickAdapter = new PickAdapter(this);
        gridView = (GridView) findViewById(R.id.image_grid);
        gridView.setAdapter(pickAdapter);
    }

    @Override
    protected void initData() {
        tv_title.setText("申请退款");
        myAdaper=new MyAdaper<ItemGoodsBean>(lstBean,R.layout.item_order_within) {
            @Override
            public void bindView(ViewHolder holder, ItemGoodsBean obj, int position) {
                holder.setImageyuan(R.id.tv_goodsImg,obj.getGoodsImg());
                holder.setText(R.id.tv_goodsName, obj.getGoodsName());
                holder.setText(R.id.tv_goodsMoney, "￥" + AllPublic.priceGSH(obj.getGoodsMoney()));
                holder.setText(R.id.tv_goodsNumber, "X" + obj.getGoodsNumber());


            }
        };
        mLoadListView.setAdapter(myAdaper);
        for (int i=0;i<lstBean.size();i++){
            double aDouble = Double.parseDouble(lstBean.get(i).getGoodsMoney());
            double v = aDouble * lstBean.get(i).getGoodsNumber();
            Log.d(TAG, "bindView: "+v);
            refundMoney=refundMoney+v;
        }
        tv_refundMoney.setText("¥"+df.format(refundMoney));
    }
    @Override
    protected void initClick() {
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SImagePicker
                        .from(activity)
                        .maxCount(4)
                        .rowCount(3)
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)
                        .forResult(REQUEST_CODE_IMAGE);
            }
        });

        ll_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = et_refund.getText().toString().trim();
                if (trim==null||"".equals(trim)){

                    toastWk("请输入退款原因");
                    return;
                }
                if (pathList.size()==0){
                    goOK("");
                }else {
                    goOK1(pathList);
                }

            }
        });





    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
             pathList =
                    data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
//            final boolean original =
//                    data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);
            pickAdapter.setNewData(pathList);
        }
    }

    /**
     * 提交1图片
     */
    private void goOK1(ArrayList<String> pathList) {
        showLoad();
        RequestParams params = new RequestParams(Constants.HTTPUPIMG);
        params.addHeader("Content-Type", "application/x-www-form-urlencoded");
        List<KeyValue> list = new ArrayList<>();
        //请求参数
        for (int i=0;i<pathList.size();i++){
            list.add(new KeyValue("file_data"+i, new File(pathList.get(i))));
            Log.d("111", "goOK1: "+pathList.get(i));
        }
        MultipartBody body = new MultipartBody(list, "UTF-8");
        params.setRequestBody(body);
        Log.d("图片", "params: "+params);
        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("提交1图片", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    int reason = jsonObject.getInt("code");
                    if (reason==0) {
                        String data = jsonObject.getString("data");
                        /**
                         * 吊起后台接口
                         */
                        goOK(data);
                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d("提交1图片-第二个", ex + "");
                ex.printStackTrace();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                Log.d("提交1图片-第三个", cex + "");
            }
            @Override
            public void onFinished() {
                Log.d("提交1图片-第四个", "onFinished");
            }
        });
    }
    //提交
    public void goOK(String certificatePhotos) {
        showLoad();
        RequestParams params = AllPublic.getParamsProductOrder(activity, "/applyRefund", false);
        params.addParameter("cmUserId",getUser().getUid());/*用户Id*/
        List<String> orderProIdList=new ArrayList<String>();
        for (int i=0;i<lstBean.size();i++){
            orderProIdList.add(lstBean.get(i).getOrder_pro_id());
            Log.e(TAG, "lstBean.size(): "+lstBean.size());
            Log.e(TAG, "lstBean.get(i).getOrder_pro_id(): "+lstBean.get(i).getOrder_pro_id());
        }
        params.addParameter("orderProIdList",orderProIdList);/*用户Id*/
        params.addParameter("refundReason",et_refund.getText().toString().trim());//
        params.addParameter("certificatePhotos",certificatePhotos);//
        Log.d("提交", "getJSON: "+params);

        //请求
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override  //成功
            public void onSuccess(String result) {
                Log.d("提交：", result);
                try {
                    JSONObject jsonObject= new JSONObject(result);
                    String reason = jsonObject.getString("code");
                    if (reason.equals("0")) {
                        toastWk("提交成功");
                        setResult(1,intent);
                        finish();

                    }else {
                        toastWk(jsonObject.getString(getResources().getString(R.string.errMsg)));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dismissLoad();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ex.printStackTrace();
                dismissLoad();
            }
            @Override
            public void onCancelled(CancelledException cex) {
                dismissLoad();
            }
            @Override
            public void onFinished() {
                dismissLoad();
            }
        });
    }
}
